#include "extractworker.h"
#include "codeprocessor.h"
#include "wordexporter.h"
#include <QDir>
#include <QFileInfo>
#include <QTextStream>

ExtractWorker::ExtractWorker(QObject *parent)
    : QObject(parent)
{
}

void ExtractWorker::setParameters(const QString &path, const QStringList &languages, const QString &savePath)
{
    m_path = path;
    m_languages = languages;
    m_savePath = savePath;
}

void ExtractWorker::process()
{
    // 统计文件总数
    int totalFiles = countFiles(m_path);
    emit totalFilesChanged(totalFiles);
    
    if (totalFiles == 0) {
        emit error(tr("没有找到符合条件的代码文件"));
        emit finished(false);
        return;
    }
    
    // 收集代码
    m_processedCode.clear();
    collectFiles(m_path);
    
    if (m_processedCode.isEmpty()) {
        emit error(tr("没有找到符合条件的代码文件"));
        emit finished(false);
        return;
    }
    
    // 合并代码并分页
    QString allCode = m_processedCode.join("\n");
    QStringList pages = CodeProcessor::splitToPages(allCode, 50);
    
    // 导出到Word文档
    bool success = WordExporter::exportToWord(pages, m_savePath);
    emit finished(success);
}

int ExtractWorker::countFiles(const QString &path)
{
    int count = 0;
    QFileInfo fileInfo(path);
    
    if (fileInfo.isFile()) {
        if (CodeProcessor::isSourceFile(path, m_languages)) {
            count++;
        }
    } else if (fileInfo.isDir()) {
        QDir dir(path);
        QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
        for (const QFileInfo &entry : entries) {
            count += countFiles(entry.filePath());
        }
    }
    
    return count;
}

void ExtractWorker::collectFiles(const QString &path)
{
    QFileInfo fileInfo(path);
    if (fileInfo.isFile()) {
        if (CodeProcessor::isSourceFile(path, m_languages)) {
            QFile file(path);
            if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                QTextStream in(&file);
                in.setCodec("UTF-8");
                QString sourceCode = in.readAll();
                // 根据文件扩展名确定语言
                QString language = CodeProcessor::getLanguageByExtension(path);
                QString processedSource = CodeProcessor::removeCommentsAndEmptyLines(
                    sourceCode, language);
                if (!processedSource.isEmpty()) {
                    m_processedCode.append("// " + path);
                    m_processedCode.append(processedSource);
                    m_processedCode.append(QString(80, '-'));
                }
                file.close();
                
                emit progressChanged(m_processedCode.size(), fileInfo.fileName());
            }
        }
    } else if (fileInfo.isDir()) {
        QDir dir(path);
        QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
        for (const QFileInfo &entry : entries) {
            collectFiles(entry.filePath());
        }
    }
} 